<template>
  <div>
    <n-spin size="large" :show="jobs.length === 0">
      <n-data-table
          :columns="jobsCol"
          :data="jobs"
          :bordered="false"
          class="cs-table"
          :max-height="320"
      />
    </n-spin>
  </div>
</template>

<script setup>
import { NDataTable, NTag, NButton, NSpin } from 'naive-ui'
import {h, onMounted, reactive, inject} from "vue";
import dayjs from "dayjs";
import axios from "axios";

const url = inject('url')

const jobs = reactive([])

const jobsCol = [
  {key: 'id', title: 'id', width: 60},
  {key: 'cluster_name', title: 'cluster_name'},
  {
    key: 'job_id',
    title: 'job_id',
    render(row) {
      return h(
          NButton,
          {
            style: {
              display: row.job_id?'block':'none'
            },
            onClick: () => window.open(row.url)
          },
          {
            default: () => row.job_id
          }
      )
    }
  },
  {
    key: 'status',
    title: 'status',
    render(row) {
      return h(
          NTag,
          {
            style: {
              marginRight: '6px'
            },
            type: row.status==='FAILED'?'error':(row.status==='RUNNING'?'warning':'success'),
            bordered: false
          },
          {
            default: () => row.status
          }
      )
    }
  },
  {
    key: 'start_time',
    title: 'start_time',
    render(row) {
      return h(
          'div',
          {},
          {
            default: () => {
              let { $y, $M, $D, $H, $m, $s} = dayjs(row.start_time)
              return `${$y}.${$M+1}.${$D} ${$H<10?'0'+$H:$H}:${$m<10?'0'+$m:$m}:${$s<10?'0'+$s:$s}`
            }
          }
      )
    }},
  {
    key: 'end_time',
    title: 'end_time',
    render(row) {
      return h(
          'div',
          {},
          {
            default: () => {
              let { $y, $M, $D, $H, $m, $s} = dayjs(row.end_time)
              return `${$y}.${$M+1}.${$D} ${$H<10?'0'+$H:$H}:${$m<10?'0'+$m:$m}:${$s<10?'0'+$s:$s}`
            }
          }
      )
    }}
]

onMounted(() => {
  let clusterNames = []
  axios.all([
    axios({url: `${url.cadUrl}/nodes?view=summary`}),axios({url: `${url.urbUrl}/nodes?view=summary`})
  ]).then(res => {
    res.forEach(c => {
      c.data.data.summary.forEach(item => {
        if(item.raylet.isHeadNode === true) {
          clusterNames.push(item.hostname)
        }
      })
    })
    axios.all([
      axios({url: `${url.cadUrl}/api/jobs/`}),axios({url: `${url.urbUrl}/api/jobs/`})
    ]).then(res => {
      let id = 1
      res.forEach((i, index) => {
        let url = i.config.url.split('/api')[0]
        i.data.forEach(job => {
          job.cluster_name = clusterNames[index]
          job.url = `${url}/ray/slave/#/jobs/${job.job_id}`
          job.id = id
          jobs.push(job)
          id++
        })
      })
    })
  })
})

</script>

<style scoped>

</style>
